package com.alibaba.pet.service.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.pet.domain.PetType;
import com.alibaba.pet.mapper.PetTypeMapper;
import com.alibaba.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    /**
     * 宠物类型树
     */
    @Override
    public List<PetType> petTypeTree() {
        List<PetType> type = petTypeMapper.findAll();
        Map<Long, PetType> map = new HashMap<>();
        for (PetType petType : type) {
            map.put(petType.getId(),petType);
        }

        ArrayList<PetType> tree = new ArrayList<>();
        for (PetType petType : type) {
           if (petType.getParentId()==null){
               tree.add(petType);
           }else {
               Long parentId = petType.getParentId();
               PetType petType1 = map.get(parentId);
               if (petType1 !=null){
                   petType1.getChildren().add(petType);
               }


           }


        }

        return tree;
    }
}
